import SparkMD5 from 'spark-md5';

const GB = 1024 ** 3;
const MB = 1024 ** 2;

const categoryTabMap = {
    all: '全部',
    document: '文档',
    audio: '音频',
    video: '视频',
    img: '图片',
    other: '其它',
};
const mimetypeRegMap = {
    doc: /^application\/(msword|vnd.openxmlformats-officedocument.wordprocessingml.document)$/i,
    xls: /^application\/(vnd.ms-excel|vnd.openxmlformats-officedocument.spreadsheetml.sheet)$/i,
    ppt: /^application\/(vnd.ms-powerpoint|vnd.openxmlformats-officedocument.presentationml.presentation)$/i,
    pdf: /^application\/pdf$/i,
    audio: /^audio\//i,
    video: /^video\//i,
    image: /^image\//i,
};

/**
 * 获取素材库枚举类型
 *
 * @param types ['all', 'document', 'audio', 'video', 'img', 'other']
 * @returns {array}
 *  [
 *    { key: 'all', value: '全部' },
 *    { key: 'document', value: '文档' },
 *    { key: 'video', value: '视频' },
 *    ...
 *  ]
 */
export function getMaterialTypeTabs(types) {
    if (types.length === 0) {
        types = ['all', 'document', 'audio', 'video', 'img', 'other'];
    }

    return types.map((type) => ({
        key: type,
        value: categoryTabMap[type],
    }));
}

/**
 * 根据文件 mimetype，获取对应类型缩写
 *
 * @param mimetype "application/msword" | "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
 * @returns {string} "doc"
 */
export function getFileType(mimetype) {
    return Object.keys(mimetypeRegMap).find((key) => mimetypeRegMap[key].test(mimetype)) || '';
}

/**
 *
 * @param limitType ["doc", "ppt", "mp3", "aac", "avi", "mp4", "png", "zip"]
 * @returns {object}
 * {
 *  "all": ["doc", "ppt", "mp3", "aac", "avi", "mp4", "png", "zip"],
 *  "document": ["doc", "ppt"],
 *  "audio": ["mp3", "aac"],
 *  "video": ["avi", "mp4"],
 *  "img": ["png"],
 *  "other": ["zip"],
 * }
 */
export function getFileAcceptType(limitType) {
    /* prettier-ignore */
    const defaultAcceptTypes = {
        document: ['doc', 'docx', 'ppt', 'pptx', 'txt', 'xls', 'xlsx', 'pdf', 'rtf', 'odt'],
        audio: ['mp3', 'wma', 'flac', 'm4a', 'ogg', 'ape', 'amr', 'wav', 'aac', 'aiff', 'caf'],
        video: ['mkv', 'rmvb', 'rm', 'wmv', 'avi', 'mp4', 'mov', 'mpg', 'asf', 'mpeg', 'vob', '3gp', 'flv', 'ts', 'mts', 'f4v', 'dv', 'm4v', 'mjpeg', 'swf', 'webm'],
        img: ['bmp', 'jpg', 'tiff', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'raw', 'png'],
        other: ['rar', 'zip'],
    };

    if (Object.prototype.toString.call(limitType) === '[object Object]') {
        return Object.assign(defaultAcceptTypes, limitType, {
            // add property all
            all: Object.values(limitType).flat(),
        });
    }

    if (Object.prototype.toString.call(limitType) === '[object Array]') {
        const types = limitType;
        if (types.length) {
            const props = Object.keys(defaultAcceptTypes);
            props.forEach((key) => {
                defaultAcceptTypes[key] = defaultAcceptTypes[key].filter((str) => types.includes(str));
            });
        }
    }

    // add property all
    const all = Object.values(defaultAcceptTypes).flat();
    return {
        ...defaultAcceptTypes,
        all,
    };
}

/**
 *
 * @param limitSize 10485760
 * @returns {object}
 * {
 *  "all": 10485760,
 *  "document": 10485760,
 *  "audio": 10485760,
 *  "video": 10485760,
 *  "img": 10485760,
 *  "other": 10485760,
 * }
 */
export function getFileAcceptSize(limitSize) {
    const defaultAcceptSizes = {
        document: 500 * MB,
        audio: 100 * MB,
        video: 2 * GB,
        img: 1 * GB,
        other: 1 * GB,
    };

    if (Object.prototype.toString.call(limitSize) === '[object Object]') {
        return Object.assign(defaultAcceptSizes, limitSize, {
            // add property all
            all: Math.max(...Object.values(limitSize)),
        });
    }

    if (Object.prototype.toString.call(limitSize) === '[object Number]') {
        const props = Object.keys(defaultAcceptSizes);
        props.forEach((key) => (defaultAcceptSizes[key] = limitSize));
    }

    // add property all
    const all = Math.max(...Object.values(defaultAcceptSizes));
    return {
        ...defaultAcceptSizes,
        all,
    };
}

export function getFileSuffix(file) {
    return file.name.replace(/.+\./, '').toLowerCase();
}

export function computeMd5(file) {
    return SparkMD5.hash(`${file.name}-${file.type}-${file.size}`);
}

 /**
   * 将文件大小格式化处理
   *
   * @param size 1024000000
   * @returns {string} '976.56MB'
   */
  export function formatFileSize(size) {
    let fsText;
  
    if (size < 1048576) fsText = (size / 1024).toFixed(2) + 'KB';
    else if (size === 1048576) fsText = '1MB'
    else if (size > 1048576 && size < 1073741824) fsText = (size / (1024 * 1024)).toFixed(2) + 'MB';
    else if (size > 1048576 && size === 1073741824) fsText = '1GB';
    else if (size > 1073741824 && size < 1099511627776) fsText = (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB';
    else fsText = '1TB+'
  
    return fsText;
  }
